package com.example.springmall.controller;

import com.example.springmall.common.R;
import com.example.springmall.entity.Goods;
import com.example.springmall.service.GoodsService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/goods")
@RequiredArgsConstructor
public class GoodsController {

    private final GoodsService goodsService;

    // 获取商品列表（所有角色用户都可访问）
    @GetMapping("/list")
    public R listGoods(HttpServletRequest request) {
        List<Goods> goodsList = goodsService.listGoods();
        return R.ok(goodsList);
    }

    // 获取商品详情（仅管理员可访问）
    @GetMapping("/{id}")
    public R getGoodsById(@PathVariable Long id, HttpServletRequest request) {
        Goods goods = goodsService.getGoodsById(id);
        if (goods == null) {
            return R.error("商品不存在");
        }
        return R.ok(goods);
    }

    // 删除商品（仅管理员可访问）
    @DeleteMapping("/{id}")
    public R deleteGoodsById(@PathVariable Long id, HttpServletRequest request) {
        boolean success = goodsService.deleteGoodsById(id);
        if (!success) {
            return R.error("删除商品失败");
        }
        return R.ok();
    }

    // 更新商品（仅管理员可访问）
    @PutMapping("/{id}")
    public R updateGoodsById(@PathVariable Long id, HttpServletRequest request) {
        boolean success = goodsService.deleteGoodsById(id);
        if (!success) {
            return R.error("删除商品失败");
        }
        return R.ok();
    }
} 